package com.cskaoyan.mall.cart.controller;

import com.cskaoyan.mall.cart.api.dto.CartInfoDTO;
import com.cskaoyan.mall.cart.service.CartService;
import com.cskaoyan.mall.common.result.Result;
import com.cskaoyan.mall.common.util.AuthContext;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

/**
 * @author Macro_Ray
 * @since 2024/6/22 下午3:00
 */
@RestController
@RequestMapping("/cart")
public class CartController {

    @Autowired
    private CartService cartService;

    /**
     * 获取购物车列表
     * @param request
     */
    @GetMapping
    public Result<List<CartInfoDTO>> cartList(HttpServletRequest request) {

        // 用户登录的userId
        String userId = AuthContext.getUserId(request);

        // 用户临时id
        String userTempId = AuthContext.getUserTempId(request);
        List<CartInfoDTO> cartList = cartService.getCartList(userId, userTempId);

        return Result.ok(cartList);
    }

    /**
     * 添加商品到购物车
     * @param skuId  商品Id
     * @param skuNum  商品数量
     */
    @GetMapping("/add/{skuId}/{skuNum}")
    public Result addToCart(@PathVariable Long skuId, @PathVariable Integer skuNum, HttpServletRequest request) {
        // skuNum表示购物车中商品的变化量，可能是1，可能是-1

        // 1. 获取userId
        String userId = AuthContext.getUserId(request);

        // 2. 当userId为空，获取用户临时id
        if (StringUtils.isBlank(userId)) {
            userId = AuthContext.getUserTempId(request);
        }
        cartService.addToCart(userId, skuId, skuNum);
        return Result.ok();
    }

    /**
     * 删除购物车指定的商品
     * @param skuId
     * @param request
     */
    @DeleteMapping("/{skuId}")
    public Result deleteCart(@PathVariable("skuId") Long skuId, HttpServletRequest request) {


        return Result.ok();
    }

    /**
     * 购物车商品的选中状态
     * @param skuId      商品Id
     * @param isChecked  选中状态，1:选中  0:未选中
     * @param request  session域
     */
    @PutMapping("/check/{skuId}/{isChecked}")
    public Result checkCart(@PathVariable Long skuId,
                            @PathVariable Integer isChecked,
                            HttpServletRequest request){

        return Result.ok();
    }

    /**
     * 删除商品的选中状态
     * */
    @DeleteMapping("/cart/checked")
    public Result deleteChecked(HttpServletRequest request) {

        return Result.ok();
    }

}
